﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Net;

using YourDataDiscovery.UPSAddressValidation.Common;


namespace YourDataDiscovery.UPSAddressValidation.Message
{
    public sealed class AVRequestSender
    {
        private AVAccessRequest avAccessRequest;
        private AddressValidationRequest addressValidationRequest;

        
        private String reqUrl;
        private String reqUserId;
        private String reqPassword;
        private String reqAccessLicenseNumber;

        #region Constructors
        public AVRequestSender(String reqUrl, String reqUserId, String reqPassword, String reqAccessLicenseNumber)
        {
            this.reqUrl = reqUrl;
            this.reqUserId = reqUserId;
            this.reqPassword = reqPassword;
            this.reqAccessLicenseNumber = reqAccessLicenseNumber;

            avAccessRequest = new AVAccessRequest(this.reqAccessLicenseNumber, this.reqUserId, this.reqPassword);
            addressValidationRequest = new AddressValidationRequest();
        }

        public AVRequestSender(String reqUrl, String reqUserId, String reqPassword, String reqAccessLicenseNumber, AddressValidationRequest addressValidationRequest)
        {
            this.reqUrl = reqUrl;
            this.reqUserId = reqUserId;
            this.reqPassword = reqPassword;
            this.reqAccessLicenseNumber = reqAccessLicenseNumber;
            this.addressValidationRequest = addressValidationRequest;

            avAccessRequest = new AVAccessRequest(this.reqAccessLicenseNumber, this.reqUserId, this.reqPassword);
        }
        #endregion

        #region Properties
        public AddressValidationRequest AddressValidationRequest
        {
            get { return addressValidationRequest; }
            set { addressValidationRequest = value; }
        }
        #endregion

        #region Methods
        public void SaveAddressValidationResponseToFile(String outputDir, String outputFile)
        {

            GetAddressValidationResponse().Save(outputDir + outputFile);
        }

        public XmlDocument GetAddressValidationResponse()
        {
            XmlDocument responseXML = new XmlDocument();
            string reqUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618)";

            //Define Post Data - Address Validation Request Message
            byte[] postData = Encoding.Default.GetBytes(avAccessRequest.GenerateXmlDocument().InnerXml.ToString() + SerializeAddressValidationRequestToString());

            HttpWebRequest webReq = ((System.Net.HttpWebRequest)(System.Net.WebRequest.Create(reqUrl)));

            try
            {
                webReq.UserAgent = reqUserAgent;
                webReq.Method = "POST";
                webReq.ContentLength = postData.Length;
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.KeepAlive = true;

                Stream webReqStream = webReq.GetRequestStream();
                webReqStream.Write(postData, 0, postData.Length);
                webReqStream.Close();


                WebResponse webRes = webReq.GetResponse();
                StreamReader webResStream = new StreamReader(webRes.GetResponseStream());

                responseXML.LoadXml(webResStream.ReadToEnd());

                webResStream.Close();
                webRes.Close();
                webReq = null;
            }
            catch (Exception err)
            {
                //Raise Error or Error Logging
            }
            finally
            {
                if (webReq != null) { webReq = null; }
                if (postData != null) { postData = null; }
            }

            return responseXML;
        }
        private String SerializeAddressValidationRequestToString()
        {
            XmlSerializer avReqSerializer = new XmlSerializer(addressValidationRequest.GetType());
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.IO.StringWriter writer = new System.IO.StringWriter(sb);
            avReqSerializer.Serialize(writer, addressValidationRequest);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sb.ToString());

            return doc.InnerXml.ToString();
        }
        #endregion
    }
}
